home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 13220 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  78 lines

  1. Path: EU.net!sun4nl!xs4all!usenet
  2. From: martijnl@xs4all.nl (Martijn Lievaart)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Forward declarations: why won't they work?
  5. Date: Sun, 24 Mar 1996 10:37:38 GMT
  6. Organization: XS4ALL, networking for the masses
  7. Message-ID: <4j38ls$m96@news.xs4all.nl>
  8. References: <4ivpp0$iut@hustle.rahul.net>
  9. NNTP-Posting-Host: mas01-09.dial.xs4all.nl
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. Theodore Sternberg <strnbrg@rahul.net> wrote:
  13.  
  14. >Forward class declarations only seem to work sometimes.  When they don't 
  15. >work, I get a compiler error to the effect that "struct foo is an 
  16. >imcomplete type".  Can anyone tell me what's going on, i.e. when forward 
  17. >class declarations are and are not possible?
  18.  
  19. >Ted Sternberg
  20. >San Jose, California, USA
  21.  
  22. A forward reference only tells the compiler 'there exists a class foo'
  23. but not what it looks like. You can use this to declare pointers and
  24. references to this class, but not use the class members or do anything
  25. where the compiler needs to now the size of the class. The error msg
  26. you get tells you the compiler needs the complete class declaration.
  27.  
  28. Why use forward references?
  29. Sometimes you need to make circular references:
  30.  
  31. class B;
  32.  
  33. class A
  34. {
  35.     B *b;
  36.     //void cannot_do_this()    { delete b; }    // see below.
  37. };
  38.  
  39. class B
  40. {
  41.     A *a;
  42. }
  43.  
  44. Here you need a forward reference because as A is declared B is still
  45. unknown.
  46.  
  47. Note that if you 'delete a member of class B' (see cannot_do_this()),
  48. you still need the complete class declaration because the compiler
  49. needs to know the sizeof(B) and if it has a destructor.
  50.  
  51. This can be solved by defining the member after class B has been
  52. declared, e.g:
  53. class B;
  54.  
  55. class A
  56. {
  57.     B *b;
  58.     void can_do_this();
  59. };
  60.  
  61. class B
  62. {
  63.     A *a;
  64. }
  65.  
  66. void A::can_do_this()
  67. {
  68.     delete b;
  69. }
  70.  
  71. Hope this clears things up,
  72. Martijn
  73.      /~~~~~| /~~~~~| /~~~~~~|~~~~~\~~~~~\~~~~|~~~~~|   We now return to our
  74.     /      |/      |/       |   o  |  o  |  |   +-|     regularly scheduled
  75.    /   /|     /|   |   /|   |  ___/  ___/   |   +-|          flame-throwing
  76. ../___/.|____/.|___|__/~|___|_|..|__|..|_____|_____|...martijnl@xs4all.nl..
  77.  
  78.